package com.pll.filter;

import com.alibaba.fastjson.JSON;
import com.pll.dto.ResponseDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginFilter
 * @Description TODO
 * @Author 小鹿
 * @Date 2025/5/23 9:39
 */
@Component
public class LoginFilter implements GlobalFilter
{
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        //创建路由白名单
        String[] whiteList = {
                "test/redisTest",
                "user/login",
                "/goods/getAllGoods",
                "/admin/send-code",
                "/order/testMsg",
                "/feeRules/getAllFeeRules"
        };
        //判断请求路径是否在白名单内
        String path = exchange.getRequest().getURI().getPath();
        for (String s : whiteList)
        {
            if (path.equals(s)){
                return chain.filter(exchange);
            }
        }
        //获取请求头携带数据 获取token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        System.out.println(token);
        /*
         *如果authorization列表为空，说明请求头不带token ==，返回提示登录
         *如果authorization不为空，说明请求头携带token，还得在访问redis做判断
         **/
        if (token !=null){
            //从redis取出token进行比对
            Object s = redisTemplate.opsForValue().get(token);
            System.out.println(s);
            if (s == null){
                //说明token不存在已过期
                ResponseDto dto = ResponseDto.err(-1,"token已过期或不存在");
                DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(JSON.toJSONBytes(dto));
                //Mono.just支持异步返回
                return exchange.getResponse().writeWith(Mono.just(wrap));
            }else {
                // 可选：续期 token
                redisTemplate.expire(token, 3600, TimeUnit.SECONDS);
                return chain.filter(exchange);
            }
        }
        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONBytes(ResponseDto.err(-1,"token为空，请重新登录")))));
    }
}